package idv.loveloser.mobilemoodle;



import idv.loveloser.mobilemoodle.ForumPostsSubjectManager.PostsAdapter;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class ForumManager extends Activity {
	private SharedPreferences sharedPreferences ;
	private SharedPreferences.Editor edit=null;
	private String sessionKey;
	private long client;
	private long courseId=-1L;
	private long forumId=-1L;
	private ListView forumListView,subjectForumListView,contentListView;
	private List<MdlForum> forums;
	private List<MdlForumDiscussions> discussions;
	private Button addForumBtn;
	private View forumManagerBottomView;
	private List<MdlForumPosts> posts;
	private Button newSubjectBtn,newReplyBtn;
	private Spinner courseSpinner,forumSpinner;
	private List<MdlCourse> courseSpinnerList;
	private List<MdlForum>  forumsSpinnerList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.forum_manager);
		newSubjectBtn=(Button) findViewById(R.id.forumManagerNewPostBtn);
		newSubjectBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				final Dialog myDialog =new Dialog(ForumManager.this);
				
				myDialog.setContentView(R.layout.forum_manager_new_subject_layout);
				final EditText subject = (EditText) myDialog.findViewById(R.id.forumManagerNewPostSubject);
				courseSpinner=(Spinner) myDialog.findViewById(R.id.courseSpinner);
				forumSpinner=(Spinner) myDialog.findViewById(R.id.forums_spinner);
				String courseResponseStr=Util.getAllCourse(client, sessionKey);
				Gson gson = new Gson();
				
//				gson=null;
				gson = new Gson();
				courseSpinnerList = gson.fromJson(courseResponseStr, new TypeToken<List<MdlCourse>>(){}.getType());
				
				
				
				String[] courseName = new String[courseSpinnerList.size()];
				for(int index=0;index<courseName.length;index++){
					MdlCourse course = courseSpinnerList.get(index);
					if(course.getFullname()!=null)
						courseName[index]=course.getFullname();
				}
				ArrayAdapter<String> courseAdapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_spinner_item,courseName);
				
				courseSpinner.setAdapter(courseAdapter);
				courseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						courseId=courseSpinnerList.get(position).getId();
						String forumResponseStr=Util.getForumListInCourse(client, sessionKey, courseId);
						Gson gson = new Gson();
						forumsSpinnerList =gson.fromJson(forumResponseStr, new TypeToken<List<MdlForum>>(){}.getType());
						if(forumsSpinnerList!=null){
							String[] forumName = new String[forumsSpinnerList.size()];
							for(int index=0;index<forumName.length;index++){
								try {
									forumName[index]=new String(forumsSpinnerList.get(index).getName().getBytes(),"UTF-8");
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							ArrayAdapter<String> forumAdapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_spinner_item,forumName);
							forumSpinner.setAdapter(forumAdapter);
							forumSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
	
								@Override
								public void onItemSelected(AdapterView<?> arg0, View arg1,
										int position, long arg3) {
									forumId=forumsSpinnerList.get(position).getId();
									
								}
	
								@Override
								public void onNothingSelected(AdapterView<?> arg0) {
									// TODO Auto-generated method stub
									forumId=forumsSpinnerList.get(0).getId();
								}
	
	
							});
						}
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
						courseId=courseSpinnerList.get(0).getId();
						
					}
				});


				
				
				Button postItBtn = (Button) myDialog.findViewById(R.id.forumManagerPostItBtn);
				final EditText message = (EditText) myDialog.findViewById(R.id.forumManagerNewPostContent);
				postItBtn.setOnClickListener(new OnClickListener() {					
					@Override
					public void onClick(View v) {
						
						Util.postInFrum(client, sessionKey, courseId, forumId, 0L, message.getText().toString(), subject.getText().toString());
						myDialog.dismiss();
					}
				});
				myDialog.show();
			}
		});
//		newReplyBtn=(Button) findViewById(R.id.forumManagerNewReplyBtn);
		forumListView = (ListView) findViewById(R.id.forumManagerListView);
		subjectForumListView=(ListView) findViewById(R.id.forumManagerSubjectListView);
		contentListView =(ListView) findViewById(R.id.forumManagerContentListView);
		sharedPreferences=getApplicationContext().getSharedPreferences("MySettings", MODE_WORLD_WRITEABLE );
		client =sharedPreferences.getLong("client", -1L);
		sessionKey=sharedPreferences.getString("sessionKey", "");
		String responseStr=Util.getAllForums(client,sessionKey);
		Gson gson = new Gson();
		forums=gson.fromJson(responseStr, new TypeToken<List<MdlForum>>(){}.getType()); 
		ForumManagerAdapter adapter = new ForumManagerAdapter(getApplication());
		adapter.setForums(forums);
		forumListView.setAdapter(adapter);
		forumListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				subjectForumListView.setAdapter(null);
				contentListView.setAdapter(null);
				MdlForum forum = forums.get(position);
				courseId = forum.getCourse();
				forumId = forum.getId();
				String responseStr=Util.getPostsSubjectsInForum(client, sessionKey, forum.getCourse(), forum.getId());
				Gson gson = new Gson();
				discussions=gson.fromJson(responseStr, new TypeToken<List<MdlForumDiscussions>>(){}.getType()); 
				ForumSubjectsAdapter subjectAdapter = new ForumSubjectsAdapter(getApplicationContext());
				subjectAdapter.setSubjects(discussions);
				subjectForumListView.setAdapter(subjectAdapter);
				subjectForumListView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						MdlForumDiscussions discussion =discussions.get(position);
						String responseStr=Util.getPostsList(client, sessionKey, discussion.getId());
						Gson gson = new Gson();
						posts=gson.fromJson(responseStr, new TypeToken<List<MdlForumPosts>>(){}.getType());
						PostContentAdapter postContentAdapter = new PostContentAdapter(getApplicationContext());
						postContentAdapter.setPosts(posts);
						postContentAdapter.setClient(client);
						postContentAdapter.setSessionKey(sessionKey);
						postContentAdapter.setForumId(discussion.getForum());
						postContentAdapter.setCourseId(discussion.getCourse());
						contentListView.setAdapter(postContentAdapter);
						contentListView.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> arg0,
									View arg1, int position, long arg3) {
								final MdlForumPosts post =posts.get(position);
								final Dialog myDialog =new Dialog(ForumManager.this);
								myDialog.setContentView(R.layout.new_reply_layout);
								final EditText messsageEditText = (EditText) myDialog.findViewById(R.id.new_reply_content);
								Button newReplyItBtn = (Button) myDialog.findViewById(R.id.newReplyItBtn);
								newReplyItBtn.setOnClickListener(new OnClickListener() {
									
									@Override
									public void onClick(View v) {
//										Util.replyPostInFrum(client, sessionKey, , courseId, post.getId(), messsageEditText.getText().toString(), subject, discussionId)
										Util.replyPostInFrum(client, sessionKey, courseId, forumId, post.getId(), messsageEditText.getText().toString(), post.getSubject(), post.getDiscussion());
										myDialog.dismiss();
										
									}
								});
								myDialog.show();
							}
						});
						
					}
				});
			}
		});
	}
	public class PostContentAdapter extends BaseAdapter{
		private List<MdlForumPosts> posts;
		private Context mContext;
		private LayoutInflater mInflater;
		private long client;
		private String sessionKey;
		private long forumId=-1L;
		private long courseId=-1L;
		public PostContentAdapter(Context context){
			this.mContext=context;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return posts.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int index=position;
			this.mInflater = LayoutInflater.from(mContext);
			
			ReplyHolder holder=null;
			if (convertView == null) {
				holder=new ReplyHolder();
				convertView = mInflater.inflate(R.layout.reply_layout, null);
				holder.replyContentTextView = (TextView) convertView.findViewById(R.id.replyContent);
				holder.replyCreateAtTextView = (TextView) convertView.findViewById(R.id.replyCreateAt);
				holder.replyUsernameTextView = (TextView) convertView.findViewById(R.id.replyUsername);
				holder.actionBtn =(Button) convertView.findViewById(R.id.reply_btn);
				holder.actionBtn.setVisibility(View.INVISIBLE);
				holder.replyMark=(ImageView) convertView.findViewById(R.id.replyMark);
				convertView.setTag(holder);
			}else{
				
				holder = (ReplyHolder) convertView.getTag();
			}
			holder.replyContentTextView.setText(posts.get(position).getMessage());
			Date date = new Date(posts.get(position).getCreated()*1000);
			holder.replyCreateAtTextView.setText(date.toString());
			String userStr=Util.getUsernameById(client, sessionKey, posts.get(position).getUserid());
			Gson gson = new Gson();
			MdlUser user=gson.fromJson(userStr, MdlUser.class);
			String firstUsername="";
			String lastUsername="";
			try{
				firstUsername=user.getFirstname();
			}catch(NullPointerException npe){
				firstUsername="";
			}
			try{
				lastUsername=user.getLastname();
			}catch(NullPointerException npe){
				lastUsername="";
			}
			String username= firstUsername+" "+lastUsername;
			holder.replyUsernameTextView.setText(username);
			if(posts.get(position).getParent()==0)
				holder.replyMark.setVisibility(View.INVISIBLE);
			else
				holder.replyMark.setVisibility(View.VISIBLE);
			
			return convertView;
		}

		public List<MdlForumPosts> getPosts() {
			return posts;
		}

		public void setPosts(List<MdlForumPosts> posts) {
			this.posts = posts;
		}

		public Context getmContext() {
			return mContext;
		}

		public void setmContext(Context mContext) {
			this.mContext = mContext;
		}

		public LayoutInflater getmInflater() {
			return mInflater;
		}

		public void setmInflater(LayoutInflater mInflater) {
			this.mInflater = mInflater;
		}

		public long getClient() {
			return client;
		}

		public void setClient(long client) {
			this.client = client;
		}

		public String getSessionKey() {
			return sessionKey;
		}

		public void setSessionKey(String sessionKey) {
			this.sessionKey = sessionKey;
		}

		public long getForumId() {
			return forumId;
		}

		public void setForumId(long forumId) {
			this.forumId = forumId;
		}

		public long getCourseId() {
			return courseId;
		}

		public void setCourseId(long courseId) {
			this.courseId = courseId;
		}

	}

}
